package com.jiliang.common.http;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * httpclient跨域调用接口工具类
 * @author
 * @since 2019/6/20
 */
public class HttpClientUtils {
    private static final Logger logger = LogManager.getLogger(HttpClientUtils.class);


    private JSONObject doPost(String url, String jsonFormString) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpPost post = new HttpPost(url);
        post.addHeader("text/plain", "UTF-8");
        post.addHeader("Content-Type", "application/json");
        post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");

        logger.info("POST请求内容：{}", jsonFormString);
        HttpClient client = HttpClientBuilder.create().build();

        if(StringUtils.isNotBlank(jsonFormString)) {
            StringEntity s = new StringEntity(jsonFormString, "UTF-8");
            post.setEntity(s);
        }
        HttpResponse httpResponse = client.execute(post);
        JSONObject response = null;
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(httpResponse.getEntity());
            response = JSONObject.parseObject(result);
        } else {
            String errorMsg = EntityUtils.toString(httpResponse.getEntity());
            throw new RuntimeException(errorMsg);
        }
        return response;
    }



}
